<template>
  <div class="password-container">
    <!-- 左侧分类列表 -->
    <div class="category-list">
      <el-card>
        <div slot="header" class="clearfix">
          <span>密码分类</span>
          <el-button type="text" @click="showAddCategoryDialog">添加分类</el-button>
        </div>
        <el-menu
          :default-active="activeCategory"
          @select="handleCategorySelect">
          <el-menu-item
            v-for="category in categories"
            :key="category.id"
            :index="category.id.toString()">
            {{ category.name }}
            <span class="count">({{ category.passwordCount }})</span>
          </el-menu-item>
        </el-menu>
      </el-card>
    </div>

    <!-- 右侧密码列表 -->
    <div class="password-list">
      <el-card>
        <div slot="header" class="clearfix">
          <span>密码列表</span>
          <el-button type="primary" @click="showAddPasswordDialog">添加密码</el-button>
        </div>
        
        <!-- 搜索栏 -->
        <el-form :inline="true" :model="queryParams" class="search-form">
          <el-form-item>
            <el-input
              v-model="queryParams.keyword"
              placeholder="搜索标题/用户名/网站"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">搜索</el-button>
          </el-form-item>
        </el-form>

        <!-- 密码列表表格 -->
        <el-table :data="passwordList" style="width: 100%">
          <el-table-column prop="title" label="标题" />
          <el-table-column prop="username" label="用户名" />
          <el-table-column prop="password" label="密码">
            <template slot-scope="scope">
              <span>{{ maskPassword(scope.row.password) }}</span>
              <el-button type="text" @click="copyPassword(scope.row)">
                复制
              </el-button>
            </template>
          </el-table-column>
          <el-table-column prop="website" label="网站" />
          <el-table-column prop="categoryName" label="分类" />
          <el-table-column label="操作" width="150">
            <template slot-scope="scope">
              <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.current"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="queryParams.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </el-card>
    </div>

    <!-- 添加/编辑分类对话框 -->
    <el-dialog :title="categoryDialogTitle" :visible.sync="categoryDialogVisible">
      <el-form :model="categoryForm" :rules="categoryRules" ref="categoryForm">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryForm.name" />
        </el-form-item>
        <el-form-item label="分类描述" prop="description">
          <el-input type="textarea" v-model="categoryForm.description" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="categoryDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCategoryForm">确定</el-button>
      </div>
    </el-dialog>

    <!-- 添加/编辑密码对话框 -->
    <el-dialog :title="passwordDialogTitle" :visible.sync="passwordDialogVisible">
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordForm">
        <el-form-item label="标题" prop="title">
          <el-input v-model="passwordForm.title" />
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="passwordForm.categoryId">
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="passwordForm.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="passwordForm.password" type="password" />
        </el-form-item>
        <el-form-item label="网站" prop="website">
          <el-input v-model="passwordForm.website" />
        </el-form-item>
        <el-form-item label="备注" prop="notes">
          <el-input type="textarea" v-model="passwordForm.notes" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitPasswordForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'PasswordManager',
  data() {
    return {
      // 分类相关
      categories: [],
      activeCategory: '',
      categoryDialogVisible: false,
      categoryDialogTitle: '',
      categoryForm: {
        id: null,
        name: '',
        description: ''
      },
      categoryRules: {
        name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
      },

      // 密码相关
      passwordList: [],
      total: 0,
      queryParams: {
        current: 1,
        size: 10,
        keyword: '',
        categoryId: null
      },
      passwordDialogVisible: false,
      passwordDialogTitle: '',
      passwordForm: {
        id: null,
        title: '',
        categoryId: null,
        username: '',
        password: '',
        website: '',
        notes: ''
      },
      passwordRules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        categoryId: [{ required: true, message: '请选择分类', trigger: 'change' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getCategories()
    this.getList()
  },
  methods: {
    // 获取分类列表
    async getCategories() {
      try {
        const response = await this.$http.get('/password/categories')
        if (response.data.code === 20000) {
          this.categories = response.data.data || []
        } else {
          throw new Error(response.data.message || '获取分类列表失败')
        }
      } catch (error) {
        console.error('获取分类列表失败:', error)
        this.$message.error(error.message || '获取分类列表失败')
      }
    },
    // 获取密码列表
    async getList() {
      try {
        const response = await this.$http.get('/password/list', { 
          params: {
            pageNo: this.queryParams.current,
            pageSize: this.queryParams.size,
            keyword: this.queryParams.keyword,
            categoryId: this.queryParams.categoryId
          }
        })
        if (response.data.code === 20000) {
          const data = response.data.data
          this.passwordList = data.rows || []
          this.total = data.total
        } else {
          throw new Error(response.data.message || '获取密码列表失败')
        }
      } catch (error) {
        console.error('获取密码列表失败:', error)
        this.$message.error(error.message || '获取密码列表失败')
      }
    },
    // 处理查询
    handleQuery() {
      this.queryParams.current = 1
      this.getList()
    },
    // 处理分页
    handleSizeChange(val) {
      this.queryParams.size = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.queryParams.current = val
      this.getList()
    },
    // 处理分类选择
    handleCategorySelect(index) {
      this.activeCategory = index
      this.queryParams.categoryId = index
      this.getList()
    },
    // 显示添加分类对话框
    showAddCategoryDialog() {
      this.categoryDialogTitle = '添加分类'
      this.categoryForm = {
        id: null,
        name: '',
        description: ''
      }
      this.categoryDialogVisible = true
    },
    // 提交分类表单
    submitCategoryForm() {
      this.$refs.categoryForm.validate(async valid => {
        if (valid) {
          try {
            let response
            if (this.categoryForm.id) {
              response = await this.$http.put('/password/category', this.categoryForm)
            } else {
              response = await this.$http.post('/password/category', this.categoryForm)
            }
            
            if (response.data.code === 20000) {
              this.$message.success(this.categoryForm.id ? '更新分类成功' : '添加分类成功')
              this.categoryDialogVisible = false
              this.getCategories()
            } else {
              throw new Error(response.data.message || '操作失败')
            }
          } catch (error) {
            console.error('保存分类失败:', error)
            this.$message.error(error.message || '操作失败')
          }
        }
      })
    },
    // 显示添加密码对话框
    showAddPasswordDialog() {
      this.passwordDialogTitle = '添加密码'
      this.passwordForm = {
        id: null,
        title: '',
        categoryId: this.activeCategory,
        username: '',
        password: '',
        website: '',
        notes: ''
      }
      this.passwordDialogVisible = true
    },
    // 处理编辑
    handleEdit(row) {
      this.passwordDialogTitle = '编辑密码'
      this.passwordForm = { ...row }
      this.passwordDialogVisible = true
    },
    // 提交密码表单
    submitPasswordForm() {
      this.$refs.passwordForm.validate(async valid => {
        if (valid) {
          try {
            let response
            if (this.passwordForm.id) {
              response = await this.$http.put('/password/update', this.passwordForm)
            } else {
              response = await this.$http.post('/password/add', this.passwordForm)
            }
            
            if (response.data.code === 20000) {
              this.$message.success(this.passwordForm.id ? '更新密码成功' : '添加密码成功')
              this.passwordDialogVisible = false
              this.getList()
            } else {
              throw new Error(response.data.message || '操作失败')
            }
          } catch (error) {
            console.error('保存密码失败:', error)
            this.$message.error(error.message || '操作失败')
          }
        }
      })
    },
    // 处理删除
    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该密码记录吗？', '提示', {
          type: 'warning'
        })
        const response = await this.$http.delete(`/password/${row.id}`)
        if (response.data.code === 20000) {
          this.$message.success('删除成功')
          this.getList()
        } else {
          throw new Error(response.data.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除密码失败:', error)
          this.$message.error(error.message || '删除失败')
        }
      }
    },
    // 密码脱敏显示
    maskPassword(password) {
      return '******'
    },
    // 复制密码
    copyPassword(row) {
      const input = document.createElement('input')
      input.value = row.password
      document.body.appendChild(input)
      input.select()
      document.execCommand('copy')
      document.body.removeChild(input)
      this.$message.success('密码已复制到剪贴板')
    }
  }
}
</script>

<style scoped>
.password-container {
  display: flex;
  gap: 20px;
  padding: 20px;
}

.category-list {
  width: 250px;
}

.password-list {
  flex: 1;
}

.search-form {
  margin-bottom: 20px;
}

.count {
  color: #999;
  font-size: 12px;
  margin-left: 5px;
}

.clearfix {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style> 
 
 
 
 
 